package xcmg.device.service;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.GenDocumentMapper;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.util.JedisUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by GYJ on 2018-01-16.
 */
@Service
public class GenDocumentService {

    /**
     * 所有单据后缀生成时，在redis中对应的key的统一的前缀, 方便定时任务批量清除重置
     */
    public static final String DOCUMENT_REDIS_KEY_COMMON_PRE = "DOCUMENT_REDIS_PRE";


    @Autowired
    private GenDocumentMapper genDocumentMapper;

    public String getDocumentNo(BillDesc billEnum) {
        //补齐八位
        String seq = String.format("%08d", genDocumentMapper.nextSeq());
        Calendar cal = Calendar.getInstance();//使用日历类
        String year = String.valueOf(cal.get(Calendar.YEAR));//得到年
        String month = String.valueOf(cal.get(Calendar.MONTH) + 1);//得到月，因为从0开始的，所以要加1
        String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));//得到天
        String pre = "0";
        if (Integer.valueOf(month) < 10) {
            month = pre.concat(String.valueOf(month));
        }
        if (Integer.valueOf(day) < 10) {
            day = pre.concat(String.valueOf(day));
        }
        //日期序列
        StringBuffer dateStr = new StringBuffer(String.valueOf(year)).append(month).append(day);
        StringBuffer documentNo = new StringBuffer(billEnum.getDesc()).append(dateStr).append(seq);

        return documentNo.toString();
    }

    /**
     * @param type         2:二级to一级；1:一级to供应商
     * @param companyOrgId
     * @return
     * @throws Exception
     */
    public String getPurchaseDocumentNo(String type, String companyOrgId, Integer selfMade, Integer isDirectCast) throws Exception {

        Calendar cal = Calendar.getInstance();//使用日历类
        String year = String.valueOf(cal.get(Calendar.YEAR));//得到年
        String month = String.valueOf(cal.get(Calendar.MONTH) + 1);//得到月，因为从0开始的，所以要加1
        String pre = "0";
        if (Integer.valueOf(month) < 10) {
            month = pre.concat(String.valueOf(month));
        }
        //日期序列
        StringBuffer dateStr = new StringBuffer(String.valueOf(year)).append('-').append(month);
        StringBuffer documentNoBuffer = new StringBuffer();

        CompanyInfoDO companyInfoDO = companyInfoMapper.item(companyOrgId);
        if (companyInfoDO == null) {
            throw new Exception("公司不存在");
        }
        String prefix = BillDesc.PurchaseNo.getDesc();
        if ("2".equals(type)) {
            prefix = BillDesc.DirectPurchaseNo.getDesc();
        }
        if (null != selfMade && 1 == selfMade) {
            prefix = BillDesc.PurchaseNoZz.getDesc();
        }
        if (null != selfMade && 2 == selfMade) {
            prefix = BillDesc.PurchaseNoJc.getDesc();
        }
        //云内公司
        if ("1".equals(type)) {
            String seq = String.format("%04d", genDocumentMapper.purchaseNextSeq());
            documentNoBuffer.append(prefix).append(companyInfoDO.getDocumentPre()).append(dateStr).append('-').append(seq);
            if (Integer.valueOf(1).equals(isDirectCast)) {
                documentNoBuffer.append('2');
            }
        } else if ("2".equals(type)) {
            String seq = String.format("%04d", genDocumentMapper.directPurchaseNextSeq());
            documentNoBuffer.append(prefix).append(companyInfoDO.getDocumentPre()).append(dateStr).append('-').append(seq);
        } else {
            String seq = String.format("%04d", genDocumentMapper.purchaseFactNextSeq());
            documentNoBuffer.append(prefix).append(companyInfoDO.getDocumentPre()).append(dateStr).append('-').append(seq);
        }

        return documentNoBuffer.toString();
    }

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    /**
     * @Author: WangKe
     * @Description: 发货通知单B+9位唯一数编码
     * @Date: 2018/5/2 0002
     */
    public String getDeliveryNo() {
        String seq = genDocumentMapper.deliveryNextSeq() + "";
        return "B" + seq;
    }

    /**
     * 生成单号：前缀字母+公司固定编号+时间yyyyMMdd+每日从0自增的4位数字
     *
     * @param billEnum
     * @param orgId
     * @return
     * @throws Exception
     */
    public String genDocumentNo(BillDesc billEnum, String orgId) {
        StringBuilder ducomentNo = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);
        if (null == companyInfoDO || StringUtils.isBlank(companyInfoDO.getDocumentPre())) {
            throw new CommonBusiExceptions("未查询到公司单据前缀");
        }
        ducomentNo.append(billEnum.getDesc()).append(companyInfoDO.getDocumentPre()).append(sdf.format(new Date()));

        // 原先KEY的格式为"_"隔开，改为英文冒号隔开，分类方便工具管理查看，修改KEY后，如果中午发布，下午使用系统因为用了新的key，
        // 导致原先自增的值取不到了，单号继续从1计算。做了向下兼容处理，如果原先key有值则将其设置到新的key上，并清空原先的key
        String documentSuffixRedisKey = DOCUMENT_REDIS_KEY_COMMON_PRE + ":" + billEnum.getDesc() + ":" + companyInfoDO.getDocumentPre();

        //从redis中取出后缀, 用单据前缀字母+公司唯一个单据编号，确保取出的每个公司每种单据后缀都从0自增
        Long documentSuffix = JedisUtils.incrByKey(documentSuffixRedisKey);

        return ducomentNo.append(String.format("%04d", documentSuffix)).toString();
    }


    public String genDocumentNoSeq(BillDesc billEnum) {
        if (null == billEnum) {
            return genDocumentMapper.getNextCode("CODE");
        }
        switch (billEnum) {
            case ZBCK:
                return genDocumentMapper.getZBCKNextCode(billEnum.getDesc());
            case ZBD:
                return genDocumentMapper.getZBDNextCode(billEnum.getDesc());
            case OutputNo:
                return genDocumentMapper.getOutputNextCode(billEnum.getDesc());
            default:
                return genDocumentMapper.getNextCode(billEnum.getDesc());
        }
    }
}
